package com.sumer.psychology.comment.application.command;

import com.sumer.psychology.comment.domain.model.*;
import com.sumer.psychology.common.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 评论应用服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/8/13
 * Time: 16:17
 */
@Transactional
public class CommentApplicationService {
    private static Logger logger = LoggerFactory.getLogger(CommentApplicationService.class);

    private CommentRepository commentRepository;

    public CommentApplicationService(CommentRepository commentRepository) {
        this.commentRepository = commentRepository;
    }

    /**
     * 创建一个新的评论
     *
     * @param aCreateCommentCommand command
     */
    public CommentId newComment(CreateCommentCommand aCreateCommentCommand) {
        Comment aComment = CommentFactory.instance().create(
                commentRepository(),
                aCreateCommentCommand);

        commentRepository().add(aComment);

        return aComment.commentId();
    }

    /**
     * 修改一个评论
     *
     * @param aChangeCommentCommand command
     */
    public void changeContent(ChangeCommentCommand aChangeCommentCommand) {
        Comment aComment = commentRepository().commentOfId(
                new CommentId(aChangeCommentCommand.changedIdentity()));

        Assert.notNull(aComment, "评论为空");

        aComment.changeContent(aChangeCommentCommand.changedContent());
    }

    /**
     * 修改带评分的评论
     *
     * @param aChangeScoredCommentCommand command
     */
    public void changeScoreContent(ChangeScoredCommentCommand aChangeScoredCommentCommand) {
        ScoredComment aComment = (ScoredComment) commentRepository().commentOfId(
                new CommentId(aChangeScoredCommentCommand.changedIdentity()));

        Assert.notNull(aComment, "评论为空");

        aComment.change(
                aChangeScoredCommentCommand.changedContent(),
                aChangeScoredCommentCommand.score());
    }

    /**
     * 删除一个评论
     *
     * @param aDeleteCommentCommand command
     */
    public void delete(DeleteCommentCommand aDeleteCommentCommand) {
        Comment aComment = commentRepository().commentOfId(
                new CommentId(aDeleteCommentCommand.deletedId()));

        if (aComment != null) {
            aComment.delete();
        }
    }

    /**
     * 根据宿主删除评论
     *
     * @param aDeleteCommentsCommand command
     */
    public void delete(DeleteCommentsCommand aDeleteCommentsCommand) {
        List<Comment> comments = commentRepository().commentsOfHost(
                new CommentHost(aDeleteCommentsCommand.hostId()));

        logger.info("{}有{}个子评论", aDeleteCommentsCommand.hostId(), comments.size());

        for (Comment aComment : comments) {
            aComment.delete();
        }
    }

    private CommentRepository commentRepository() {
        return commentRepository;
    }

}
